import BaseRewardAd, { RewardADState } from "../base/BaseRewardAd";

export default class VivoRewardAd extends BaseRewardAd {
    isShow = false;
    createVideoAd(id) {
        this.rewardedVideoAd = qg.createRewardedVideoAd({
            posId: id
        });
        this.rewardedVideoAd.onLoad(this.onLoad.bind(this));
        this.rewardedVideoAd.onError(this.onError.bind(this));
        this.rewardedVideoAd.onClose(this.onClose.bind(this));
    }


    open(callback) {
        this.rewardCallback = callback;
        if (this.state == RewardADState.success) {
            this.show()
        } else {
            this.load(true);
        }
    }

    onError(err) {
        console.log('VivoRewardAd error ', err)
        this.state == RewardADState.error
        this.showToast('广告拉取失败')
        if (this.rewardCallback) {
            this.rewardCallback(false)
        }
    }

    onLoad() {
        console.log('视频加载成功 ')
        this.state = RewardADState.success
        if (this.isShow) {
            this.show()
            this.isShow = false;
        }

    }
    onClose(res) {
        // ModuleManager.publicAudio().playMusic('audio/cartoon-time')
        // this.setState(SDKState.close)
        this.state = RewardADState.close;
        if (res && res.isEnded || res === undefined) {
            console.log('视频结束关闭 ')
            // 正常播放结束，可以下发游戏奖励
            if (this.rewardCallback) {
                this.rewardCallback(true)
            }

        } else {
            // 播放中途退出，不下发游戏奖励
            console.log('视频中途关闭 ')
            if (this.rewardCallback) {
                this.rewardCallback(false);
                // ToastController.instance().intoLayer('ui.not_finish');
            }
        }
        this.load(false)
    }


    load(flag) {
        this.isShow = flag;
        this.rewardedVideoAd.load()
    }


    show() {
        this.state == RewardADState.open
        this.rewardedVideoAd.show().then(() => {
            // this.setState(SDKState.open)
            console.log(' 激励视频展示成功 ')
            // ModuleManager.publicAudio().stopMusic()
        }).catch(() => {
            // 失败重试
            this.rewardedVideoAd.load()
                .then(() => {
                    console.log(' 激励视频加载成功 ')
                    this.rewardedVideoAd.show()
                })
                .catch(err => {
                    // this.channel.showToast('广告拉取失败')
                    console.log(' 激励视频重试失败 err ', err)
                    // this.setState(SDKState.loadFail)
                    // callback(false)
                    // SDKManager.getChannel().showShare(this.rewardCallback)

                })
        })
    }

    showToast(text) {
        qg.showToast({
            message: text
        })
    }


}